package com.matrix.im.service;

import com.matrix.common.constant.RedisConstants;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Service
@RequiredArgsConstructor
public class SessionService {

    private final StringRedisTemplate redisTemplate;

    @Getter
    private final String instanceId = UUID.randomUUID().toString();

    public void userConnected(Long userId) {
        String key = RedisConstants.buildKey(RedisConstants.IM_SESSION_KEY_PREFIX, userId);
        redisTemplate.opsForValue().set(key, instanceId, 30, TimeUnit.MINUTES);
    }

    public void userDisconnected(Long userId) {
        String key = RedisConstants.buildKey(RedisConstants.IM_SESSION_KEY_PREFIX, userId);
        String storedInstanceId = redisTemplate.opsForValue().get(key);
        if (instanceId.equals(storedInstanceId)) {
            redisTemplate.delete(key);
        }
    }

    public boolean isUserConnectedToCurrentInstance(Long userId) {
        String key = RedisConstants.buildKey(RedisConstants.IM_SESSION_KEY_PREFIX, userId);
        String targetInstanceId = redisTemplate.opsForValue().get(key);
        return instanceId.equals(targetInstanceId);
    }
}
